<?php
/**
 * Created by User: wene<china_wangyu@aliyun.com> Date: 2019/4/11 Time: 17:32
 */

namespace think\restful\validate;

use think\restful\Base;
use think\restful\exception\ApiException;

/**
 * Class Param API参数校验类
 * @package think\restful\validate
 */
class Param extends Base
{
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 执行API参数验证
     * @param \think\restful\Api $api
     * @param string $action
     */
    public function execute(\think\restful\Api $api,string $action):void
    {
        try{
            $apiReflexClass = new \think\restful\reflex\Reflex($api);
            $apiReflexClassDocs = $apiReflexClass->action($action);
            $apiReflexClassRoute = $apiReflexClassDocs['route'];
            $this->route($apiReflexClassRoute);

            $apiReflexClassParam = $apiReflexClassDocs['param'];
            $rules = $this->rules($apiReflexClassParam);
            if ($rules !== null){
                $validate = $this->validate->make($rules);
                if (!$validate->check($this->param)){
                    ApiException::exception('参数错误：' . $validate->getError());
                }
            }
        }catch (\Exception $exception){
            ApiException::exception('500 '.$exception->getMessage());
        }
    }

    /**
     * 过滤获取 rules
     * @param array $reflexData
     * @return array|null
     */
    public function rules(array $reflexData):?array
    {
        if(empty($reflexData)) return null;
        $rules = null;
        foreach ($reflexData as $reflexDatum){
            if(empty($reflexDatum['rule'])) continue;
            $rules[$reflexDatum['name']] = $reflexDatum['rule'];
        }
        return $rules;
    }

    /**
     * 检验路由的请求方式是否合法
     * @param array $route
     */
    protected function route(array $route)
    {
        $userMethod = $this->request->method();
        if (strtolower($userMethod) !== strtolower($route['method'])){
            ApiException::exception('API请求类型不合法~');
        }
    }
}